// Fill out your copyright notice in the Description page of Project Settings.

#include "Kismet/GameplayStatics.h"
#include "Teleport_Library.h"
#include "EngineUtils.h"

void UTeleport_Library::FindActorLocationFromClass(UObject* WorldContextObject, AActor* actor, TSubclassOf<AActor> ActorClass, FVector& NeastLocation, FVector& FurthestLocation) {
	if (ActorClass)
	{
		if (UWorld* World = GEngine->GetWorldFromContextObject(WorldContextObject, EGetWorldErrorMode::LogAndReturnNull))
		{
			FVector ActorLocation = actor->GetActorLocation();

			float NearstDistance = 999999999; 
			float FurthestDistance = 0;

			for (TActorIterator<AActor> It(World, ActorClass); It; ++It)
			{
				FVector TempLocation = It->GetActorLocation();
				float TempDistance = FVector::Distance(ActorLocation, TempLocation);

				if (NearstDistance >= TempDistance) {
					NearstDistance = TempDistance;
					NeastLocation = TempLocation;
				}

				if (FurthestDistance<TempDistance) {
					FurthestDistance = TempDistance;
					FurthestLocation = TempLocation;
				}
			}
		}
	}
}

void UTeleport_Library::FindAllActorsOfClassByDistance(UObject* WorldContextObject, AActor* actor, TSubclassOf<AActor> ActorClass, TArray<AActor*>& OutActors) {
	QUICK_SCOPE_CYCLE_COUNTER(UGameplayStatics_GetAllActorsOfClass);
	OutActors.Reset();

	if (ActorClass)
	{
		if (UWorld* World = GEngine->GetWorldFromContextObject(WorldContextObject, EGetWorldErrorMode::LogAndReturnNull))
		{
			FVector ActorLocation = actor->GetActorLocation();
			TMap<float, AActor*> MapActor;

			for (TActorIterator<AActor> It(World, ActorClass); It; ++It)
			{
				MapActor.Add(FVector::Distance(ActorLocation, It->GetActorLocation()), *It);
			}

			MapActor.KeySort(TLess<float>());

			for (auto It : MapActor) {
				AActor* Actor = It.Value;
				OutActors.Add(Actor);
			}
		}
	}
 }